package com.daocheng.dc.book.gateway.filter;

import cn.dev33.satoken.stp.StpUtil;
import com.daocheng.framework.common.constant.GlobalConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @ClassName AddUserId2HeaderFilter
 * @author: 稻城
 * @date: 2025/3/24
 * @Version 1.0
 * @description: TODO
 */
@Component
@Slf4j
public class AddUserId2HeaderFilter implements GlobalFilter {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("==================> TokenConvertFilter");
        Long userId = null;
        try {
            userId = StpUtil.getLoginIdAsLong();
        } catch (Exception e) {
            // 若没有登录，则直接放行
            return chain.filter(exchange);
        }
        log.info("## 当前登录的userId: {}", userId);
        Long finalUserId = userId;
        ServerWebExchange newExchange = exchange.mutate()
                .request(builder -> builder.header(GlobalConstant.USER_ID, String.valueOf(finalUserId)))
                .build();
        return chain.filter(newExchange);
    }
}